import 'package:flutter/material.dart';

extension HexColor on Color {
  /// 将带有透明度的十六进制颜色字符串转换为 Color
  static Color fromHex(String hexString) {
    final buffer = StringBuffer();
    if (hexString.startsWith('#')) {
      buffer.write(hexString.substring(1));
    } else {
      buffer.write(hexString);
    }

    String hex = buffer.toString();
    if (hex.length == 6) {
      hex = 'FF$hex'; // 添加不透明的 alpha 值
    } else if (hex.length == 8) {
      // 已经包含 alpha 值，不需要处理
    } else {
      throw ArgumentError('Invalid hex color format: $hexString');
    }

    return Color(int.parse(hex, radix: 16));
  }

  /// 将不带透明度的十六进制颜色字符串转换为不透明的 Color
  static Color fromHexWithoutAlpha(String hexString) {
    final buffer = StringBuffer();
    if (hexString.startsWith('#')) {
      buffer.write(hexString.substring(1));
    } else {
      buffer.write(hexString);
    }

    String hex = buffer.toString();
    if (hex.length == 3) {
      // 处理简写形式，如 #333
      final String r = hex[0];
      final String g = hex[1];
      final String b = hex[2];
      hex = 'FF$r$r$g$g$b$b';
    } else if (hex.length == 6) {
      hex = 'FF$hex'; // 添加不透明的 alpha 值
    } else {
      throw ArgumentError('Invalid hex color format: $hexString');
    }

    return Color(int.parse(hex, radix: 16));
  }
}
